package internal

import (
	controllor "fitness/internal/controller"
	fitnessController "fitness/internal/controller/fitness"
	"fitness/internal/dao"
	fitnessDao "fitness/internal/dao/fitness"
	"fitness/internal/service"
	fitnessService "fitness/internal/service/fitness"
	"fitness/pkg/middleware"
	"fitness/pkg/tools"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"sync"
)

var (
	Instance     *Container
	instanceOnce sync.Once
)

type Container struct {
	ControllerContainer        *controllor.ControllerContainer
	ServiceContainer           *service.ServiceContainer
	DaoContainer               *dao.DaoContainer
	FitnessControllerContainer *fitnessController.ControllerContainer
	FitnessServiceContainer    *fitnessService.ServiceContainer
	FitnessDaoContainer        *fitnessDao.DaoContainer

	HandlerError *tools.HandlerError
}

func GetInstance(db *gorm.DB, logger *zap.Logger, engine *gin.Engine) *Container {
	instanceOnce.Do(func() {
		//工具类单例
		handlerError := tools.NewHandlerError(logger)
		//dao单例
		instanceDao := dao.CreateDaoInstance(db, logger)
		//中间件
		instanceRbac := middleware.CreateRbacInstance(instanceDao)
		//service单例
		instanceService := service.CreateServiceInstance(instanceDao, handlerError, logger)
		//controller单例
		instanceController := controllor.CreateControllerInstance(instanceService, instanceRbac)
		//fitness的dao
		instanceFitnessDao := fitnessDao.CreateFitnessDaoInstance(db, logger)
		//fitness的service
		instanceFitnessService := fitnessService.CreateFitnessServiceInstance(instanceFitnessDao, logger)
		//fitness的controller
		instanceFitnessController := fitnessController.NewFitnessControllerContainer(instanceFitnessService, instanceRbac)

		//启动接口
		//用户接口
		instanceController.UserController.InitApiRouter(engine)
		//验证码登录
		instanceController.AuthController.InitApiRouter(engine)
		//菜单权限
		instanceController.MenuController.InitApiRouter(engine)
		//部门
		instanceController.DeptController.InitApiRouter(engine)
		//字典
		instanceController.DictController.InitApiRouter(engine)
		//角色
		instanceController.RoleController.InitApiRouter(engine)
		//日志
		instanceController.LogController.InitApiRouter(engine)
		//预约
		instanceFitnessController.DetailController.InitApiRouter(engine)
		//微信客户
		instanceFitnessController.UserController.InitApiRouter(engine)
		//controller单例
		Instance = &Container{
			ControllerContainer:        instanceController,
			ServiceContainer:           instanceService,
			DaoContainer:               instanceDao,
			FitnessControllerContainer: instanceFitnessController,
			FitnessServiceContainer:    instanceFitnessService,
			FitnessDaoContainer:        instanceFitnessDao,
			HandlerError:               handlerError,
		}
	})
	return Instance
}
